import hashlib
import json
import uuid
from datetime import datetime, timedelta

import jwt
from django.core.paginator import Paginator
from django.forms import model_to_dict
from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt

from lianxi20250919.models import User, Book, Borrow


# Create your views here.
def jiami(pwd):
    return hashlib.md5(pwd.encode()).hexdigest()
@csrf_exempt
def login0919(request):
    data=json.loads(request.body)
    # 判空
    if data['username']=='' or data['password']=='':
        return JsonResponse(
            {
                'msg':'用户名和密码不能为空'
            }
        )
    # 数据库中是否有用户
    if User.objects.filter(username=data['username']).exists() is False:
        return JsonResponse(
            {
                'msg':'用户名错误'
            }
        )
    # 输入密码是否正确
    u=User.objects.get(username=data['username'])
    if User.objects.get(username=data['username']).password!=jiami(data['password']):
        return JsonResponse(
            {
                'msg':'密码错误',
                'password':jiami(data['password'])
            }
        )
    # 生成token
    mi='123456'
    t=datetime.now()+timedelta(days=0.5)
    pay={
        'userid':u.userid,
        'exp':int(t.timestamp()),
        'role':u.role
    }
    token=jwt.encode(pay,mi)
    # 返回成功
    return JsonResponse(
        {
            'msg':'登录成功',
            'token':token
        }
    )
def get_books(request):
    data=Book.objects.all()
    l=[]
    title=request.GET.get('title')
    status=request.GET.get('status')
    size=request.GET.get('size') or 10
    page=request.GET.get('page',1)
    # 支持按title和status筛选
    if title:
        data=data.filter(title=title)
    if status:
        data=data.filter(status=status)
    total=len(data)
    data=Paginator(data,size).get_page(page)
    for i in data:
        l.append(
            {
                'bookid':i.bookid,
                'title':i.title,
                'author':i.author,
                'price':i.price,
                'stock':i.stock,
                'status':i.status
            }
        )
    return JsonResponse(
        {
            'msg':'查询成功',
            'item':l,
            'total':total,
            'page':page
        }
    )
@csrf_exempt
def post_borrows(request):
    data=json.loads(request.body)
    token=request.META.get('HTTP_TOKEN')
    if not token:
        return JsonResponse(
            {
                'msg':'请先登录'
            }
        )
    mi='123456'
    try:
        pay=jwt.decode(token,mi,algorithms=['HS256'])
    except jwt.ExpiredSignatureError:
        return JsonResponse(
            {
                'msg':'token已过期'
            }
        )
    except jwt.InvalidTokenError:
        return JsonResponse(
            {
                'msg':'token无效'
            }
        )
    a=Borrow.objects.create(
        borrowid=uuid.uuid4(),
        book_id_id=data['book_id'],
        user_id_id=pay['userid'],
        borrow_date=datetime.now(),
        return_date=datetime.now(),
        status=1
    )
    return JsonResponse(
        {
            'msg':'添加成功',
            'item':model_to_dict(a)
        }
    )
def get_borrows(request):
    token=request.META.get('HTTP_TOKEN')
    mi='123456'
    pay=jwt.decode(token,mi,algorithms=['HS256'])
    if pay['role']==1:
        data=Borrow.objects.all()
        l=[]
        for i in data:
            l.append(
                {
                    'borrowid':i.borrowid,
                    'book_id': i.book_id_id,
                    'user_id':i.user_id_id,
                    'borrow_data':i.borrow_date,
                    'return_data':i.return_date,
                    'status':i.status
                }
            )
        return JsonResponse(
            {
                'msg':'查询成功',
                'item':l
            }
        )
    else:
        data=Borrow.objects.filter(user_id_id=pay['userid'])
        l = []
        for i in data:
            l.append(
                {
                    'borrowid': i.borrowid,
                    'book_id': i.book_id_id,
                    'user_id': i.user_id_id,
                    'borrow_data': i.borrow_date,
                    'return_data': i.return_date,
                    'status': i.status
                }
            )
        return JsonResponse(
            {
                'msg': '查询成功',
                'item': l
            }
        )